package com.sc.common.util;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


/**
 * @author 作者 E-mail:
 * @version 创建时间：2020年5月18日 下午9:44:28
 * 类说明 邮件激活 发送邮件
 */
@Component
public final class MailUtil {
    private static final String USER = "q1115088512@qq.com";//邮箱地址
    private static final String PASSWORD = "yfsjntydntqpbaah";//邮箱授权码

    public static boolean sendMail(String to, String text, String title) {
        try {
            final Properties pro = new Properties();
            pro.put("mail.smtp.auth", "true");
            pro.put("mail.smtp.host", "smtp.qq.com");

            //发件人账号
            pro.put("mail.user", USER);
            pro.put("mail.password", PASSWORD);

            //授权信息
            Authenticator authenticator = new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    //用户名，密码
                    String username = pro.getProperty("mail.user");
                    String password = pro.getProperty("mail.password");
                    return new PasswordAuthentication(username, password);
                }
            };
            //使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(pro, authenticator);
            //创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            //设置发件人
            String username = pro.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);
            //设置邮件标题
            message.setSubject(title);
            //设置邮件的内容
            message.setContent(text, "text/html;charset=UTF-8");
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}